package top.lyc829.leetcode.T94;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {


    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        doWork(root, list);
        return list;
    }


    // 迭代版本，利用堆栈
    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }

            root = stack.pop();
            list.add(root.val);
            root = root.right;
        }
        return list;
    }


    // 递归版本
    private void doWork(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        doWork(root.left, list);
        list.add(root.val);
        doWork(root.right, list);

    }

    public static void main(String[] args) {
        Solution s = new Solution();
        TreeNode treeNode1 = new TreeNode(1, null, new TreeNode(2, new TreeNode(3, null, null), null));
        List<Integer> res = s.inorderTraversal2(treeNode1);

        System.out.println(res.toString());
    }


}